(function (moduleName4Html, global, factory) {
    if (typeof module !== 'undefined' && typeof exports === 'object') {//CommonJS(NodeJS)
        module.exports = factory(global);
    } else if (typeof define === 'function' && (define.amd || define.cmd)) {//AMD   CMD
        define( function () { factory(global); } );
    } else {//ES(Browser)
        global[moduleName4Html] = factory(global);
    }
}("core", this, function (global) {
    'use strict';

    var jsonConfigs = {};

    if (!!$) {
        window.jsrender = $;
    }

    var templateHOC = {
        strReplace: function (sourceStr, pattern, flags, replaceStr) {
            return sourceStr.replace(new RegExp(pattern, flags), replaceStr);
        },

        printf: function ( data ) {
            console.log( data );
        },

        extendData: {
            testMap: {test: "000"},
            testList: [111,222],
        },
    }

    var templateMap = {};
    window.console = window.console || (function () {
        var c = {}; c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile
                 = c.clear = c.exception = c.trace = c.assert = function () { };
        return c;
    })();
    // $(window).resize(function () {
    //     var win = $(this).width();
    //     if (win < window.screen.width) { //宽度小于1493时，按1493和窗口实际宽度计算等比
    //         $("body").css("width", window.screen.width);
    //         $("body").css("zoom", win / window.screen.width);
    //     } else {
    //         $("body").css("zoom", "normal");
    //     }
    // })
    //跨域问题
    jQuery.support.cors = true;
    jQuery.ajaxSetup({
        xhr: function() {
            if(window.ActiveXObject){
                return new window.ActiveXObject("Microsoft.XMLHTTP");
            }else{
                return new window.XMLHttpRequest();
            }
        }
    });
      // placeholder
    var core = {
        load: function (elementId, url, callback, isReplace) {
            $("#" + elementId).load(url, function (resp, status, xhr) {
                if (status === "error") {
                    alert("load: " + elementId + "\n" + url + "\n" + xhr.status + "\n" + xhr.statusText);
                    return;
                }

                if (isReplace) {
                    $("#" + elementId)[0].outerHTML = resp;
                }

                if (callback) {
                    callback();
                }
            });
        },

        loadSync: function (elementId, url, callback, isReplace) {
            $.ajaxSetup({ async: false });
            core.load(elementId, url, callback, isReplace);
            $.ajaxSetup({ async: true });
        },

        getJsonConfigSync: function (url) {
            if(!jsonConfigs[url]){
                // $.getJSON(url, function (json) {
                //     jsonConfigs[url] = json
                // });

                //$.ajaxSetup({ async: false });
                $.ajax({
                    async: false,
                    dataType: "text",
                    url: url,
                    headers: {
                        token:$.cookie('token')
                     },
                    crossDomain: true,
                    // beforeSend: function (xhr) {  
                    //     xhr.setRequestHeader("Cache-Control", "no-cache");
                    //     //xhr.setRequestHeader("Pragma", "no-cache");
                    // },
                    success: function( jsonStr ) {
                        //jsonConfigs[url] = JSON.parse(jsonStr);
                        //jsonConfigs[url] = eval('('+jsonStr+')');
                        jsonConfigs[url] = new Function("return " + jsonStr)()
                    },
                    error:function(res){
                        console.log(res)
                    }
                });
                //$.ajaxSetup({ async: true });
            }
            return jsonConfigs[url];
        },

        useTemplate: function (templateId, elementId, data, helpersOrContext, noIteration) {
            var template = templateMap[templateId]
            if (!template) {
                template = jsrender.templates(base.htmlDecode($("#" + templateId).html()));
                templateMap[templateId] = template

                $("#" + templateId).outerHTML = "";
            }

            var htmlOutput = template.render(data, $.extend(templateHOC, helpersOrContext), noIteration);
            //$("#" + elementId).html(htmlOutput);
            $("#" + elementId)[0].innerHTML = htmlOutput;
        },

        useTemplateAuto: function (elementId, data, helpersOrContext, noIteration) {
            var arr = templateMap[elementId], template, targetElement;
            if (arr) {
                template = arr[0];
                targetElement = arr[1];
            } else {
                var element = $("#" + elementId)
                template = jsrender.templates(base.htmlDecode(element.html()));
                targetElement = element.parent();
                templateMap[elementId] = [template, targetElement]
            }

            var htmlOutput = template.render(data, $.extend(templateHOC, helpersOrContext), noIteration);
            targetElement.html(htmlOutput);
            //targetElement[0].innerHTML = htmlOutput;
        },

        useTemplateAll: function (data, helpersOrContext, noIteration) {
            //var elements = $('script[type="text/x-jsrender"]')
            var elements = $('script[type="text/html"]')
            for (var i = 0; i < elements.length; i++) {
                var template = jsrender.templates(base.htmlDecode(elements[i].innerHTML));
                var htmlOutput = template.render(data, $.extend(templateHOC, helpersOrContext), noIteration);
                elements[i].outerHTML = htmlOutput;
            }
        },
        GetObjectKey:function(){
           // Object.keys兼容ie8
              if (!Object.keys) {
                    Object.keys = (function () {
                    var hasOwnProperty = Object.prototype.hasOwnProperty,
                    hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
                    dontEnums = [
                            'toString',
                            'toLocaleString',
                            'valueOf',
                            'hasOwnProperty',
                            'isPrototypeOf',
                            'propertyIsEnumerable',
                            'constructor'
                    ],
                    dontEnumsLength = dontEnums.length;
         return function (obj) {
            if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
            var result = [];
            for (var prop in obj) {
              if (hasOwnProperty.call(obj, prop)) result.push(prop);
            }
            if (hasDontEnumBug) {
              for (var i=0; i < dontEnumsLength; i++) {
                if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
              }
            }
            return result;
          }
        })()
      
      };
      if (!Object.keys) Object.keys = function(o) {
        if (o !== Object(o))
          throw new TypeError('Object.keys called on a non-object');
        var k=[],p;
        for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p);
        return k;
      }
        },
      // 跳转到详情页
        toDetail:function(tempId,htmlName){
                 $(tempId).click(function (e) {
                 if ($(e.target).hasClass('title')) {
                // 跳转
                        window.open (htmlName+'?data=' + encodeURIComponent(JSON.stringify($(e.target).attr('data-id'))));
                        }
                     })
                  },
        notFindPage:function(){
            window.location='/admin/page/404.html'
        },
        indexBanner:function(){
             var index=0,
                 slideFlag = true,
                 length=$(".roll-news-image>div").length;

             function showImg(i){
                  $(".roll-news-image>div") 
                  .eq(i).stop(true,true).fadeIn(800) 
                  .siblings("div").hide(); 
                  $(".roll-news-index li").removeClass("roll-news-index-hover"); 
                  $(".roll-news-index li").eq(i).addClass("roll-news-index-hover") ;
                  $(".roll-news-title a") 
                  .eq(i).stop(true,true).fadeIn(800) 
                  .siblings("a").hide(); 
                }
                showImg(index);
                
                $(".roll-news-index li").click(function(){
                    index = $(".roll-news-index li").index(this);
                    showImg(index);
                    slideFlag = false;
                });	
                
                function autoSlide() {
                    setInterval(function() {
                        if(slideFlag) {
                            showImg((index+1) % length);
                            index = (index+1)%length;
                        }
                        slideFlag = true;
                    }, 5000);
                }	
                autoSlide();
        }
                
}
                
return core;
}));
